class DictionariesController < ApplicationController

  def index
    @dictionaries = Dictionary.paginate(:page => params[:page],
                                        :order => 'name')
  end

  def show
    @dictionary = Dictionary.find_by_id(params[:id])

    if @dictionary
      DictServiceHelper.get_dictionary_info(@dictionary)
    else
      flash[:error] = 'Dictionary not found!'
      redirect_to dictionaries_path and return
    end
  end

  def synchronise
    MiddleMan.worker(:model_synchronizer_worker).enq_synchronise_dictionaries(:job_key => "#{Time.now.to_s(:short)}_dictionaries_synchronization")

    flash[:notice] = 'Dictionaries synchronization has been scheduled successfully.<br>Synchronization will take place in a few seconds.'
    redirect_to dictionaries_path
  end

  def define
    @word = Word.find_by_id(params[:word_id])
    @dictionary = Dictionary.find_by_id(params[:id])    

    if @dictionary.nil? || @word.nil?
      flash[:error] = 'Invalid expression submitted!'
      redirect_to :back and return
    end

    @word_definitions = WordDefinition.for(@word, @dictionary, 
                                          :force_look_up => true,
                                          :page => params[:page])
  end

  def setup_search_form_for
    render :nothing => true and return unless request.xhr?

    @dictionary = Dictionary.find_by_id(params[:id])

    if @dictionary
      render :partial => 'search_form', :locals => {:dictionary => @dictionary}
    else
      render :nothing => true
    end

    return
  end

  def define_ajax
    render :nothing => true and return unless request.xhr?
    
    @word = Word.find_or_create_by_text(params[:word][:text].to_s.downcase)
    @dictionary = Dictionary.find_by_id(params[:id])

    if @dictionary.nil? || @word.nil?
      @div = :definitions
      @class_name = WordDefinition.class_name
      render :template => 'shared/error' and return
    end

    @word_definitions = WordDefinition.for(@word, @dictionary, 
                                            :force_look_up => true,
                                            :limit => 1)
    @word.delete if @word_definitions.empty?
  end

end
